<?php

namespace App\Http\Controllers\Mini;

use App\Models\Configs;
use App\Models\IntegralLogs;
use App\Models\UserInfos;
use App\Models\Users;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use GuzzleHttp\Client;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    /**
     * 用户登录
     * @route api.login.login
     * @param mobile 手机号
     * @param password 密码
     * @param user_type 1密码登陆 2手机验证码登录
     */
    public function login(Request $request)
    {
        try{
            Log::info('in mini login');
            $user_infos = auth()->guard('mini')->user();
            if($user_infos){
                auth()->guard('mini')->logout();
                $request->session()->forget('uri.intented');
                Users::where('id',$user_infos['id'])->update(['openid'=>'']);
                $user_infos=array();
            }

            Log::info($user_infos);
            $open_id = (string)$request->post('openid');
            Log::info($open_id);
            if(!$user_infos){
                $params = [
                    'mobile' => (string)$request->post('mobile'),
                    'password' => (string)$request->post('password'),
                ];
                $open_id = (string)$request->post('openid');
                $code = (string)$request->post('code');
                $user_type = (int)$request->post('user_type');// 1密码登陆 2手机验证码登录

                if($user_type == 2) {//验证码登录
                    if(empty($params['mobile']) || empty($code)){
                        return response()->json(["code"=>0, "msg"=>'参数错误']);
                    }
                    //检查验证码是否正确
                    $cache = cache()->get('sms-'.$params['mobile']);
                    if(empty($cache)) return response()->json(["code"=>0, "msg"=>'短信验证码已过期']);//过期
                    if($cache['code'] != $code) return response()->json(["code"=>0, "msg"=>'短信验证码输入错误']);
                    cache()->delete('sms-'.$params['mobile']);//删除验证码
                    //登录
                    $user_info = Users::where('mobile',$params['mobile'])->where('status','<>',-1)->first();
                    if($user_info&&$params['mobile']){
                        $users = \Auth::loginUsingId($user_info['id']);
                    }else{
                        return response()->json(["code"=>0, "msg"=>'用户名或密码错误']);
                    }
                }else {//密码登陆
                    //验证
                    $rules = ['mobile' => 'required', 'password' => 'required',];
                    $msgs = ['mobile.required' => '请填写手机号码', 'password.required' => '请填写密码',];
                    $validator = validator()->make($params,$rules,$msgs);
                    if ($validator->fails()) {
                        return response()->json(["code"=>0, "msg"=>$validator->errors()->first()]);
                    }
                    //登录
                    $auth = auth()->guard('mini')->attempt(['mobile' => $params['mobile'],'password' => $params['password']]);
                    if ($auth) {
                        $request->session()->regenerate();
                        $this->clearLoginAttempts($request);
                        $users = auth()->guard('mini')->user();
                    }else{
                        return response()->json(["code"=>0, "msg"=>'用户名或密码错误']);
                    }
                }
                if($users['status'] == -1){
                    return response()->json(["code"=>0, "msg"=>'当前用户不存在']);
                }
                //当天第一次登陆送积分
                $integral = Configs::getConfig('integral');//积分
                if (trim(@date('Y-m-d', strtotime($users['login_at']))) != trim(date('Y-m-d'))) {
                    $integral_login = 0;
                    if($users['type'] == 1) {//HR登陆送积分
                        $integral_login = $integral['hr_login'];
                    }elseif ($users['type'] == 2) {//供应商登陆送积分
                        $integral_login = $integral['bus_login'];
                    }
                    Users::where('id',$users['id'])->increment('integral',$integral_login);
                    //添加日志记录
                    $integral_arr = [
                        'user_id' => $users['id'],
                        'user_name' => $users['username'],
                        'integral' => '+'.$integral_login,
                        'desc' => '每日首次登陆送积分',
                        'type' => 1,
                    ];
                    IntegralLogs::create($integral_arr);
                }
                $data=['login_at' => date('Y-m-d H:i:s'), 'login_ip' => $request->ip()];
                if($open_id){
                    $data['openid']=$open_id;
                }
                Users::where('id',$users['id'])->update($data);
                $users['openid']=$open_id;
                return response()->json(["code" => 1, "msg" => "登录成功", "data" => $users]);
            }else{
                $open_id = (string)$request->post('openid');
                if($open_id&&!$user_infos['openid']){
                    Users::where('id',$user_infos['id'])->update(['openid'=>$open_id]);
                }
                return response()->json(["code" => 1, "msg" => "已经登录", "data" => $user_infos]);
            }
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户注册
     * @route api.login.register
     * @param mobile 手机号
     * @param password 密码
     * @param type 类型：1人力HR，2供应商
     * @param code 验证码
     */
    public function register(Request $request)
    {
        try{
            $params = [
                'mobile' => (string)$request->post('mobile'),
                'password' => (string)$request->post('password'),
                'type' => (int)$request->post('type'),//类型：1人力HR，2供应商
            ];
            //检查验证码是否正确
            $code = (string)$request->post('code');
            if (empty($code)) return response()->json(["code"=>0, "msg"=>'请输入验证码']);
            $cache = cache()->get('sms-'.$params['mobile']);
            if(empty($cache)) return response()->json(["code"=>0, "msg"=>'短信验证码已过期']);//过期
            if($cache['code'] != $code) return response()->json(["code"=>0, "msg"=>'验证码输入错误']);
            cache()->delete('sms-'.$params['mobile']);//删除验证码
            //检测手机号是否被注册
            $check_mobile = Users::getUserInfo(['mobile' => $params['mobile']]);
            if (!empty($check_mobile)) {
                return response()->json(["code"=>0, "msg"=>'该手机号已经注册']);
            }

            $integral = Configs::getConfig('integral');//积分
            $base = Configs::getConfig('base');//获取头像
            $now = date('Y-m-d H:i:s');
            $user_sn = 'HR'.substr(time(),-6);
            $data = [
                'avatar' => $base['default_avatar'],
//                'user_sn' => $user_sn,
                'username' => $user_sn,
//                'nickname' => $user_sn,
                'mobile' => $params['mobile'],
                'password' => bcrypt($params['password']),
                'register_ip' => $request->ip(),
                'login_at' => $now,//最近一次登陆时间
                'login_ip' => $request->ip(),
                'type' => $params['type'],
                'created_at' => $now,
                'updated_at' => $now,
            ];
            //注册送积分
            if($params['type'] == 1) {
                $data['integral'] = $integral['hr_register'];
            }elseif($params['type'] == 2) {
                $data['integral'] = $integral['bus_register'];
                $data['status'] = 2;
            }
            $user_id = Users::insertGetId($data);//数据入库
            //信息存入扩展表
            $data_info = [
                'user_id' => $user_id,
            ];
            UserInfos::create($data_info);
            //添加日志记录
            $integral_log = [
                'user_id' => $user_id,
                'user_name' => $params['mobile'],
                'desc' => '注册送积分',
                'type' => 1,
            ];
            if($params['type'] == 1) {
                $integral_log['integral'] = '+'.$integral['hr_register'];
            }elseif($params['type'] == 2) {
                $integral_log['integral'] = '+'.$integral['bus_register'];
            }
            IntegralLogs::create($integral_log);

            return response()->json(["code"=>1, "msg"=>'注册成功']);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 找回密码
     * @route api.login.findPwd
     * @param mobile 手机号
     * @param password 新密码
     * @param code 短信验证码
     */
    public function findPwd(Request $request)
    {
        try{
            $mobile = (string)$request->post('mobile');
            $password = (string)$request->post('password');
            $code = (string)$request->post('code');
            if(empty($mobile) || empty($password) || empty($code)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            if(!preg_match('/^((13|14|15|16|17|18|19)[0-9]\d{8})$/', $mobile))  return response()->json(["code"=>0, "msg"=>'请填写正确的手机号码']);

            $info = Users::where('mobile',$mobile)->where('status','<>',-1)->first(['id','status']);
            if(!empty($info)){
                //检查验证码是否正确
                $cache = cache()->get('sms-'.$mobile);
                if(empty($cache)) return response()->json(["code"=>0, "msg"=>'短信验证码已过期']);//过期
                if($cache['code'] != $code) return response()->json(["code"=>0, "msg"=>'短信验证码输入错误']);
                cache()->delete('sms-'.$mobile);//删除验证码

                Users::where('id',$info['id'])->update(['password' => bcrypt($password)]);
                return response()->json(["code"=>1, "msg"=>'找回成功,请重新登录']);
            }else{
                return response()->json(["code"=>0, "msg"=>'该用户不存在']);
            }
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 退出登录
     * @route api.login.logout
     * @param user_id 用户id
     */
    public function logout(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');

            auth()->guard('mini')->logout();
            $request->session()->forget('uri.intented');
            Users::where('id',$user_id)->update(['openid'=>'']);
            return response()->json(["code"=>1, "msg"=>'退出成功']);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 根据openid获取用户并自动登录
     * @route api.login.getUserByOpenid
     */
    public function getUserByOpenid(Request $request){
        $code = $request->get('code', '');
        $open_id = $request->get('openid', '');
        Log::info('getUserByOpenid openid:'.$open_id);
        if ($open_id>"") {
            // 通过 code 获取 open_id
            Log::info('weixin openid:'.$open_id);
            //先判断openid是否绑定，再拉取用户信息
            $user = Users::where('openid',"$open_id")->first();
            Log::info('openid login:'.$user);
            if($user){
                Auth::loginUsingId($user['id']);
                return response()->json([
                    "code" => 1,
                    "msg" => "登录成功",
                    "data" => $user
                ]);
            }
            else{

                return response()->json([
                    "code" => 1,
                    "msg" => "openid未绑定",
                    'openid' => $open_id,
                    "data" => ''
                ]);
            }
        }
        if ($code) {
            // 通过 code 获取 open_id
            Log::info('weixin oauth2:'.$code);
            $client = new Client();
            $url = sprintf("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                env('WEIXIN_KEY'), env('WEIXIN_SECRET'), $code);
            try {
                $res = $client->request('GET', $url, ['timeout' => 1.5]);
                $res = $res->getBody();
                Log::info('weixin oauth2:'.$res);
                $res = json_decode($res);
                $open_id='';
                //先判断是否有值，然后通过access_token和openid拉取用户信息
                if (isset($res->access_token)) {
                    $open_id = $res->openid;
                }

                $user = Users::where('openid',"$open_id")->first();
                if($user&&$open_id){
                    Auth::loginUsingId($user['id']);
                    return response()->json([
                        "code" => 1,
                        "msg" => "登录成功",
                        "data" => $user
                    ]);
                }
                else{
                    Log::error('weixin oauth2:'.json_encode($res));
                    return response()->json([
                        "code" => 1,
                        "msg" => "openid未绑定",
                        'openid' => $open_id,
                        "data" => ''
                    ]);
                }
            } catch(\Throwable $e) {
                Log::error('Fail to call api'.$e->getMessage());
                return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
            }
        }
    }
}